package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;

import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;

import com.eryos.android.cigarettecounter.beans.History;
import com.eryos.android.cigarettecounter.beans.SmokeAverage;
import com.eryos.android.cigarettecounter.beans.SmokeCounter;
import com.eryos.android.cigarettecounter.charts.Chart;
import com.eryos.android.cigarettecounter.charts.HistoChart;
import com.eryos.android.cigarettecounter.charts.LineChart;
import com.eryos.android.cigarettecounter.database.CigaretteDatabase;

public class HistoryActivity extends RootActivity {


    /** *************** UI Elements *************** **/	
    private WebView detailChartView;
    private WebView historyChartView;
    private TextView averageLabel;
    private TextView totalLabel;
    private TextView costLabel;

    /** *************** Instance Variables *************** **/	
    private History type;
    
    private int CHART_WIDTH = 320;
    private int CHART_HEIGHT = 200;
    private double CHART_TITLE = 12.5;

    private ArrayList<SmokeCounter> countValues;
    private ArrayList<SmokeAverage> averageValues;
	
    private double average = -1;
    private double cost = -1;
    private int total = -1;
	
    private String detailChartData			= "";
    private String detailChartLabel			= "";
    private int    detailsMaxValue			= -1;
	
    private String histoChartData			= "";
    private String histoChartLabel			= "";
    private double histoMaxValue			= -1;
    
	/* ********************************************************************** */
	/*                  REAL     METHODS                                      */
	/* ********************************************************************** */

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Show charts
        if ( type.isWeekly() ){
            showWeeklyDetailChart();
            showWeeklyHistoryChart();        	
        }else if(type.isMonthly()){
            showMonthlyDetailChart();
            showMonthlyHistoryChart();        	
        }
        
    }

    /**
     * Method used to initialized all UI elements
     */
	protected void initUI(){
	    setContentView(R.layout.history);

	    showWaitingMessage();
	    
	    detailChartView 	= (WebView) findViewById(R.id.Chart_Detail);    	
	    historyChartView 	= (WebView) findViewById(R.id.Chart_Histo);
	    averageLabel 		= (TextView)findViewById(R.id.history_average_value);
	    totalLabel 			= (TextView)findViewById(R.id.history_total_value);
	    costLabel 			= (TextView)findViewById(R.id.history_cost_value);
    	
        int screenWidth = this.getWindow().getWindowManager().getDefaultDisplay().getWidth();
        
        if ( screenWidth < 400 ){
        	CHART_WIDTH = (int) (0.67 * screenWidth);
        	CHART_HEIGHT = (int) (0.625 * CHART_WIDTH);
        	CHART_TITLE = 10.5;
        }

	}
	
	/**
	 * 
	 */
	protected void initValues(){
        countValues		= new ArrayList<SmokeCounter>();
        averageValues	= new ArrayList<SmokeAverage>();

        type = (History)this.getIntent().getExtras().getSerializable(History.class.toString());

        if ( type.isWeekly() ){
            countValues 	= db.getWeeklyDetails();
        	average 		= db.getWeeklyAverage();
        	averageValues 	= db.getLastWeeksAverage();
        	cost 			= db.getWeeklyCost();
        	total 			= db.getWeeklyCount();
        }else if(type.isMonthly()){
            countValues 	= db.getMonthlyDetails();
            average 		= db.getMonthlyAverage();
        	averageValues 	= db.getLastMonthsAverage();
        	cost 			= db.getMonthlyCost();
        	total 			= db.getMonthlyCount();
        }
        
        String averageValueLabel = new String(averageLabel.getText()+"");    	
        averageLabel.setText("     "+averageValueLabel.replaceAll("#", average+""));

        String totalValueLabel = new String(totalLabel.getText()+"");    	
        totalLabel.setText("     "+totalValueLabel.replaceAll("#", total+""));
        
        String costValueLabel = new String(costLabel.getText()+"");    	
        costLabel.setText("     "+costValueLabel.replaceAll("#", cost+""));

        hideWaitingMessage();
	}
    
    
	/**
	 * 
	 */
    protected void showMonthlyDetailChart(){
    	String lastDate = "";
    	int lastDayOfMonth = 31;
    	int i = 0;

    	if ( countValues.size() > 0 ){

    		SmokeCounter firstSmoke = countValues.get(0);
    		int first = firstSmoke.getDate().get(Calendar.DAY_OF_MONTH);
    		
    		lastDayOfMonth = CigaretteDatabase.getLastDayOfMonth(firstSmoke.getDate().get(Calendar.MONTH)-1);
    		
    		if ( first > 1 ){
    			for ( int y = 1 ; y < first; y++)
    	        	detailChartData = detailChartData + "0" + Chart.DATA_SEPARATOR;
    		}

        	for (SmokeCounter smoke : countValues){
        		i++;
            	lastDate = smoke.getLabel();
            	detailChartData = detailChartData + "" + smoke.getValue() + Chart.DATA_SEPARATOR;
            	if ( smoke.getValue() > detailsMaxValue )
            		detailsMaxValue = smoke.getValue();
        	}
        	i += first;
        	for ( int j = i ; j <= lastDayOfMonth ; j ++ )
            	detailChartData = detailChartData + "0" + Chart.DATA_SEPARATOR;

    	}

        LineChart lc = new LineChart();
        lc.setAvgLegend(getResources().getString(R.string.history_month_average_legend));
        lc.setValueLegend(getResources().getString(R.string.history_month_value_legend));
        lc.setWidth(CHART_WIDTH);
        lc.setHeight(CHART_HEIGHT);
        lc.setMaxYValue(detailsMaxValue);
        lc.setMaxXValue(lastDayOfMonth);
        lc.setData(detailChartData); 
        lc.setAverage(average);
        lc.setTitle(getResources().getString(R.string.history_month_detail_label)+" "+getMonthLabel(lastDate));
        lc.setTitleSize(CHART_TITLE);
        
    	detailChartView.loadUrl(lc.getURL());
    }
    
    
    protected void showMonthlyHistoryChart(){
    	
    	for (SmokeAverage smoke : averageValues){
    		histoChartData = histoChartData + "" + smoke.getValue() + Chart.DATA_SEPARATOR;
    		histoChartLabel = histoChartLabel + "" + getMonthFirstLetter( new Integer(smoke.getLabel()) ) + Chart.LABEL_SEPARATOR;
        	if ( smoke.getValue() > histoMaxValue )
        		histoMaxValue = smoke.getValue();
    	}
        
    	HistoChart hst = new HistoChart();
    	hst.setYAxisLabel(histoChartLabel); 
        hst.setData(histoChartData);
        hst.setMaxVal( new BigDecimal(histoMaxValue).intValue()+1);
        hst.setWidth(CHART_WIDTH);
        hst.setHeight(CHART_HEIGHT);
        hst.setTitle(getResources().getString(R.string.history_month_histo_label));
        hst.setTitleSize(CHART_TITLE);
        
    	historyChartView.loadUrl(hst.getURL());
    }
    
    
    protected void showWeeklyDetailChart(){
    	for (SmokeCounter smoke : countValues){
        	detailChartData = detailChartData + "" + smoke.getValue() + Chart.DATA_SEPARATOR;
        	detailChartLabel = detailChartLabel + "" + getDayFirstLetter(new Integer(smoke.getLabel())) + Chart.LABEL_SEPARATOR;
        	if ( smoke.getValue() > detailsMaxValue )
        		detailsMaxValue = smoke.getValue();
    	}
        
    	HistoChart hst = new HistoChart();
    	hst.setYAxisLabel(detailChartLabel); 
        hst.setData(detailChartData);
        hst.setMaxVal( new BigDecimal(detailsMaxValue).intValue()+1);
        hst.setWidth(CHART_WIDTH);
        hst.setHeight(CHART_HEIGHT);
        hst.setBarColor("3072F3");
        hst.setTitle(getResources().getString(R.string.history_week_detail_label));
        hst.setTitleSize(CHART_TITLE);
        
    	detailChartView.loadUrl(hst.getURL());
    }
    
    
    protected void showWeeklyHistoryChart(){
    	
    	for (SmokeAverage smoke : averageValues){
    		histoChartData = histoChartData + "" + smoke.getValue() + Chart.DATA_SEPARATOR;
    		histoChartLabel = histoChartLabel + "" + smoke.getLabel() + Chart.LABEL_SEPARATOR;
        	if ( smoke.getValue() > histoMaxValue )
        		histoMaxValue = smoke.getValue();
    	}

    	HistoChart hst = new HistoChart();
    	hst.setYAxisLabel(histoChartLabel); 
        hst.setData(histoChartData);
        hst.setMaxVal( new BigDecimal(histoMaxValue).intValue()+1);
        hst.setWidth(CHART_WIDTH);
        hst.setHeight(CHART_HEIGHT);
        hst.setTitle(getResources().getString(R.string.history_week_histo_label));
        hst.setTitleSize(CHART_TITLE);

    	historyChartView.loadUrl(hst.getURL());
    }

    
    
	/* ********************************************************************** */
	/*                  STATIC   METHODS                                      */
	/* ********************************************************************** */
    
    /**
     * Last day of the month with data ( date format : 23/01/2011 )
     */
    public String getMonthLabel( String _date){
    	try {
			String month = _date.substring(3,5);
			Integer i = new Integer(month);

			switch(i){
				case 1:
					return getResources().getString(R.string.month_january_full);
				case 2:
					return getResources().getString(R.string.month_february_full);
				case 3:
					return getResources().getString(R.string.month_march_full);
				case 4:
					return getResources().getString(R.string.month_april_full);
				case 5:
					return getResources().getString(R.string.month_may_full);
				case 6:
					return getResources().getString(R.string.month_june_full);
				case 7:
					return getResources().getString(R.string.month_july_full);
				case 8:
					return getResources().getString(R.string.month_august_full);
				case 9:
					return getResources().getString(R.string.month_september_full);
				case 10:
					return getResources().getString(R.string.month_october_full);
				case 11:
					return getResources().getString(R.string.month_november_full);
				case 12:
					return getResources().getString(R.string.month_december_full);
			}
		} catch (Exception e) {
			System.out.println("getMonthLabel : "+_date);
			e.printStackTrace();
			return "NA";
		}
	
	return "NA";
    }
    
    public String getMonthFirstLetter(int month){
    	switch(month){
	    	case 1:
	    		return getResources().getString(R.string.month_january);
	    	case 2:
	    		return getResources().getString(R.string.month_february);
	    	case 3:
	    		return getResources().getString(R.string.month_march);
	    	case 4:
	    		return getResources().getString(R.string.month_april);
	    	case 5:
	    		return getResources().getString(R.string.month_may);
	    	case 6:
	    		return getResources().getString(R.string.month_june);
	    	case 7:
	    		return getResources().getString(R.string.month_july);
	    	case 8:
	    		return getResources().getString(R.string.month_august);
	    	case 9:
	    		return getResources().getString(R.string.month_september);
	    	case 10:
	    		return getResources().getString(R.string.month_october);
	    	case 11:
	    		return getResources().getString(R.string.month_november);
	    	case 12:
	    		return getResources().getString(R.string.month_december);
    	}
    	
    	return "NA";
    }
    
    public String getDayFirstLetter(int day){
    	switch(day){
    	case 0:
    		return getResources().getString(R.string.week_sunday);
    	case 1:
    		return getResources().getString(R.string.week_monday);
    	case 2:
    		return getResources().getString(R.string.week_tuesday);
    	case 3:
    		return getResources().getString(R.string.week_wednesday);
    	case 4:
    		return getResources().getString(R.string.week_thursday);
    	case 5:
    		return getResources().getString(R.string.week_friday);
    	case 6:
    		return getResources().getString(R.string.week_saturday);
    	}
    	
    	return "NA";
    }

}
